/**
 * 
 */
package org.footito.android.api;

import org.footito.android.data.database.ProviderAdapter;
import org.footito.android.tools.FootitoException;
import org.footito.android.tools.Log;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Target : http://api.footito.fr/avatar/list http://api.footito.fr/avatar/list?updated_after=###TON_TIMESTAMP####
 * 
 * @author Julien
 * 
 */
public class TeamListApiHandler extends DefaultHandler {
	private boolean inTeam;
	private boolean inName;
	private boolean inPicture;
	private boolean inLink;

	private final static String TEAMTAG = "team";
	private final static String NAMETAG = "name";
	private final static String PICTURETAG = "picture";
	private final static String LINKTAG = "link";
	private final static String idTag = "id";

	public final static String URL_API = "http://api.footito.fr/avatar/list";
	public final static String URL_API_UPDATED_AFTER = "updated_after";

	private String name;
	private String picture;
	private String link;
	private int id;
	private ProviderAdapter db;

	/**
	 * 
	 */
	public TeamListApiHandler(ProviderAdapter db) {
		this.db = db;
	}

	@Override
	public void startDocument() throws SAXException {
	}

	@Override
	public void endDocument() throws SAXException {
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (localName.equals(TEAMTAG)) {
			this.inTeam = true;
			id = Integer.parseInt(attributes.getValue(idTag));
		} else if (localName.equals(NAMETAG)) {
			this.inName = true;
			name = "";
		} else if (localName.equals(PICTURETAG)) {
			this.inPicture = true;
			picture = "";
		} else if (localName.equals(LINKTAG)) {
			this.inLink = true;
			link = "";
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (localName.equals(TEAMTAG)) {
			this.inTeam = false;
			try {
				db.insertTeam(id, name, picture, link);
			} catch (FootitoException e) {
				Log.e("Exception: FootitoException: " + e.getMessage());
			}
		} else if (localName.equals(NAMETAG)) {
			this.inName = false;
		} else if (localName.equals(PICTURETAG)) {
			this.inPicture = false;
		} else if (localName.equals(LINKTAG)) {
			this.inLink = false;
		}
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		if (inName) {
			this.name += new String(ch, start, length);
		} else if (inLink) {
			this.link += new String(ch, start, length);
		} else if (inPicture) {
			this.picture += new String(ch, start, length);
		}
	};
}
